GApp.Schemes = {
    list: [],
    url: '/?url=configSchemes/schemes'
};

(function (P) {
    P.getScheme = function (id) {
        var scheme = null;
        $.each(P.list, function (i, v) {
           if (v.id === id) {
               scheme = P.list[i];
           } 
        });
        return scheme;
    },
    
    P.updateTable = function (url) {
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url
        })
        .done (function (data) {
            var tmp = [];
            var json = JSON.parse (data);
            
            P.list.length = 0;
            
            $('#dataTables-schemes > tbody').html ('');
            $.each(json, function (i, v) {
                tmp.push ('<tr class="odd gradeX">');
                tmp.push ('<td align="center">');
                tmp.push ('<a href="#" onclick="GApp.Schemes.viewScheme (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-gear fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.Schemes.modifyScheme (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-pencil-square fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.Schemes.removeScheme (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-minus-square fa-lg"></i></a>');
                tmp.push ('</td>');
                tmp.push ('<td>' + v.name + '</td>');
                tmp.push ('<td>' + v.description + '</td>');
                tmp.push ('</tr>');
                P.list.push (v);
            });
            
            $('#dataTables-schemes > tbody').html (tmp.join (''));
        })
        .fail (function () {
            console.log ('ERROR: updateTable');
        });
    },
    
    P.sendScheme = function (data, okCallback, errorCallback) {
        var url = ($('#schemeIdForm').val () !== '') ? 'modifyScheme' : 'addScheme';
        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configSchemes/' + url,
            data: {
                id: data.id,
                name: data.name,
                description: data.description
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.sendRemoveScheme = function (data, okCallback, errorCallback) {        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configSchemes/removeScheme',
            data: {
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.validateAndCommitModal = function () {
        var errors = 0;
        var scheme = {
            id: $('#schemeIdForm').val () || null,
            name: $('#schemeNameForm').val () || null,
            description: $('#schemeDescriptionForm').val ()
        };

        if (!scheme.name || scheme.name.length == 0) {
            $('#schemeNameForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#schemeNameForm').parent ().removeClass ('has-error');
        }

        if (errors === 0) {
             P.sendScheme (scheme, 
                 function () {
                    // OK
                    $('#schemeModalDlg').modal ('hide');
                    P.updateTable (GApp.Schemes.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: validateAndCommitModal');
                 }
             );
        }
    },
    
    P.confirmFormScheme = function (scheme) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>¿Quieres eliminar el esquema seleccionado?</label>');
        form.push ('</div>');
        
        $('#schemeModalLabel').text ('Eliminar esquema');
        $('#schemeAcceptModalDlg').on ('click', function () {
           P.sendRemoveScheme (scheme, 
                 function () {
                    // OK
                    $('#schemeModalDlg').modal ('hide');
                    P.updateTable (GApp.Schemes.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: confirmFormScheme');
                 }
            );
        });
        
        $('#schemeModalBody').html (form.join (''));
        $('#schemeModalDlg').modal ();
        $('#schemeModalDlg').on ('hidden.bs.modal', function () {
            $('#schemeAcceptModalDlg').off ('click');
            $('#schemeModalDlg').off ('hidden.bs.modal');
        });
        
        if (scheme) {
            $('#schemeIdForm').val (scheme.id);
        }
        
        return false;
    },
    
    P.showFormScheme = function (title, scheme) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>Nombre</label>');
        form.push ('<input class="form-control" placeholder="Nombre del esquema" id="schemeNameForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Descripción</label>');
        form.push ('<input class="form-control" placeholder="Descripción del esquema" id="schemeDescriptionForm">');
        form.push ('<input type="hidden" id="schemeIdForm">');
        form.push ('</div>');
        
        $('#schemeModalLabel').text (title);
        $('#schemeAcceptModalDlg').on ('click', function () {
           P.validateAndCommitModal ();
        });
        
        $('#schemeModalBody').html (form.join (''));
        $('#schemeModalDlg').modal ();
        $('#schemeModalDlg').on ('hidden.bs.modal', function () {
            $('#schemeAcceptModalDlg').off ('click');
            $('#schemeModalDlg').off ('hidden.bs.modal');
        });
        
        if (scheme) {
            $('#schemeNameForm').val (scheme.name);
            $('#schemeDescriptionForm').val (scheme.description);
            $('#schemeIdForm').val (scheme.id);
        }
        
        return false;
    },

    P.newScheme = function () {        
        return P.showFormScheme ('Nuevo esquema');
    },

    P.modifyScheme = function (schemeId) {
        return P.showFormScheme ('Modificar esquema', P.getScheme (schemeId));
    }
    
    P.removeScheme = function (schemeId) {
        return P.confirmFormScheme (P.getScheme (schemeId));
    }
    
    P.viewScheme = function (schemeId) {
        window.location = GApp.baseURL + '?url=configAreas&id=' + schemeId;
    }
} (GApp.Schemes));

if (document.URL.indexOf ('url=configSchemes') > 0) {
    $(document).ready (function () {
        GApp.Schemes.updateTable (GApp.Schemes.url);
    });
}
